<template>
  <el-dialog
    class="clinic-operate-dialog"
    :width="dialogWidth"
    append-to-body
    top="5vh"
    title="收费明细"
    :close-on-click-modal="false"
    :visible.sync="visible"
    style="cursor:default;"
  >
    <div class="clinic-operate-from">
      <el-container>
        <el-main>
          <!-- 步骤条 -->
          <div class="step" ref="step">
            <el-steps>
              <el-step title="待收费" :status="curStep === 0 ? 'finish':''"></el-step>
              <el-step title="已收费" :status="curStep === 1 ? 'finish':''"></el-step>
              <el-step title="已审核" :status="curStep === 2 ? 'finish':''"></el-step>
              <el-step title="已调剂" :status="curStep === 3 ? 'finish':''"></el-step>
              <el-step title="退费中" :status="curStep === 5 ? 'finish':''"></el-step>
              <el-step title="已退费" :status="curStep === 4 ? 'finish':''"></el-step>
            </el-steps>
          </div>
          <!-- 患者信息 -->
          <personal
            :address="addressInfoData"
            :orderData="orderInfo"
            :infoNo="info.infoNo"
            :data="consultInfo"
            ref="personal"
          >
          </personal>
          <!-- table  -->
          <div class="table" :style="style" v-loading="loading" style="padding-left:15px">
            <el-tabs v-model="activeName" @tab-click="handleClick" >
              <template v-for="(item,index) in infoDrugs" >
                <template v-if="item.orderCondition == 5">
                  <el-tab-pane  :key="index"  :label="`${durtType(item.prescriptionType)}${durtSource(item.source)} （已作废）`" :name="`${index}`"></el-tab-pane>
                </template>
                 <template v-else-if="item.payStatus == 3">
                  <el-tab-pane  :key="index"  :label="`${durtType(item.prescriptionType)}${durtSource(item.source)} （已退款）`" :name="`${index}`"></el-tab-pane>
                </template>
                <template v-else>
                  <el-tab-pane  :key="index"  :label="`${durtType(item.prescriptionType)}${durtSource(item.source)}`" :name="`${index}`"></el-tab-pane>
                </template>
              </template>
            </el-tabs>
            <el-table v-if="visible" ref="table" :data="info.infoDrugs" @selection-change="onSelectionChange">
              <template v-if="isReissue">
                <el-table-column
                  :selectable="selectableReissue"
                  type="selection"
                  width="50"
                />
              </template>

              <el-table-column label="序号" type="index" width="55"></el-table-column>
              <el-table-column label="商品名称" prop="drugName" width="200"></el-table-column>
              <el-table-column label="药品类型" prop="drugType">
                <template slot-scope="scope">
                  <drugType :value="scope.row.drugType"></drugType>
                </template>
              </el-table-column>
              <el-table-column label="单价" prop="price" v-if="isDeliver">
                <template slot-scope="scope">{{formatMoney(scope.row.price)}}</template>
              </el-table-column>
              <template v-if="info.num && info.prescriptionType != 2">
                <el-table-column label="数量*剂数" prop="quantity">
                  <template slot-scope="scope">{{ (scope.row.quantity / info.num) + scope.row.packUnit }}*{{ info.num }}</template>
                </el-table-column>
              </template>
              <template v-else>
                <el-table-column label="数量" prop="quantity">
                  <template slot-scope="scope">{{ (scope.row.quantity) + scope.row.packUnit }}</template>
                </el-table-column>
              </template>
              <el-table-column label="折扣" prop="discount" v-if="isDeliver">
                <template slot-scope="scope">
                  <template v-if="operate === 1000">
                    <columnClickEdit
                      @change="onChangeDiscount"
                      dataType="number"
                      :value="scope.row.discount"
                      :eternal="true"
                      :row="scope.row"
                      :max="100"
                      :min="0"
                    >
                      <span>{{ discountText(scope.row.discount) }}</span>
                    </columnClickEdit>
                  </template>
                  <template v-else>{{ discountText(scope.row.discount) }}</template>
                </template>
              </el-table-column>

              <template v-if="isReissue">
                <el-table-column label="补发数量" prop="operateNum">
                  <template slot-scope="{row}">
                    <el-input-number
                      :disabled="info.prescriptionType === 1 || info.prescriptionType === 3"
                      v-model="row.operateNum"
                      :controls="true"
                      :min="0"
                    />
                  </template>
                </el-table-column>
              </template>
              <template v-else>
                <el-table-column label="折后金额" prop="discountPrice" v-if="isDeliver">
                  <template slot-scope="scope">{{formatMoney(scope.row.discountPrice, 4)}}</template>
                </el-table-column>
              </template>

              <template v-if="operate === 2 || operate === 3">
                <el-table-column label="已退数量" prop="refundCount">
                  <template slot-scope="scope">
                    <template v-if="scope.row.refundCount > 0">
                      {{ scope.row.refundCount + scope.row.packUnit }}
                    </template>
                    <template v-else>0</template>
                    <!-- <template v-else>{{ scope.row.refundCount }}</template> -->
                  </template>
                </el-table-column>
                <template v-if="curStep === 5">
                  <el-table-column label="将退数量" prop="operateNum">
                    <template slot-scope="{row}">
                      <template v-if="row.operateNum > 0">
                        <el-input v-model="row.operateNum" disabled />
                      </template>
                    </template>
                  </el-table-column>
                </template>
                <template v-else>
                  <el-table-column label="退款入库" prop="refundType">
                    <template slot-scope="{row}">
                      <template v-if="row.refundType === 0">否</template>
                      <template v-else>是</template>
                    </template>
                  </el-table-column>
                </template>
              </template>
            </el-table>
          </div>
        </el-main>
        <!-- 左边费用明细 -->
        <asideForm
          :isAdjust="orderCheckStatus != 1 && orderCheckStatus != 2"
          :prescriptionType="info.prescriptionType"
          :refundTypeFlag="orderInfo.refundType"
          :details="expenseDetails"
          :reasonInfo="reasonInfo"
          :refundList="refundList"
          :isReissue="isReissue"
          :total="expenseTotal"
          v-if="isRight != 99"
          :curStep="curStep"
          :operate="operate"
          ref="asideForm"
        >
        </asideForm>
      </el-container>
    </div>
    <div slot="footer" class="dialog-footer">
      <template v-if="payStatus != 4 && !isReissue && !incompleteRefund">
        <el-button
          v-if="operate === 0 && orderCheckStatus !=5 "
          :loading="submitLoading"
          @click="onClickPay"
          type="primary"
        >收费</el-button>
        <template v-if="operate != 4">
          <el-button
            v-if="operate === 1 || operate === 2"
            :loading="submitLoading"
            @click="onPrintDetails"
            type="primary"
          >打印</el-button>
        </template>
        <template v-if="operate === 1 || operate === 2">
          <el-button
            v-if="orderCheckStatus === 1"
            @click="onClickCheck(2)"
            :loading="submitLoading"
            type="primary"
          >审方</el-button>
          <el-button
            v-if="orderCheckStatus === 2"
            @click="onClickCheck(5)"
            :loading="submitLoading"
            type="primary"
          >调剂</el-button>
        </template>
        <template v-if="dataForm == 2 && orderInfo">
          <!-- <template v-if="orderInfo.deliveryType === 1 && orderInfo.orderType === 2 && orderInfo.orderCondition === 3">
            <el-button
              :loading="submitLoading"
              @click="onOkOrder"
              type="primary"
            >确认发货</el-button>
          </template> -->
          <template v-if="orderInfo.deliveryType === 1 && orderInfo.orderType === 1 && orderInfo.orderCondition === 3">
            <el-button
              :loading="submitLoading"
              @click="onOkOrder"
              type="primary"
            >确认发货</el-button>
          </template>
          <template v-if="orderInfo.deliveryType === 2 && orderInfo.orderCondition === 3">
            <el-button
              :loading="submitLoading"
              @click="onOkOrder"
              type="primary"
            >确认自提</el-button>
          </template>
        </template>
        <template v-if="orderInfo.orderType == 1">
          <template v-if="info.payStatus == 0 && info.orderCondition != 5">
            <el-button
              :loading="submitLoading"
              @click="onClickDel"
              type="danger"
            >作废</el-button>
          </template>
        </template>
        <!-- <template v-else>
          <template v-if="info.payStatus == 1">
            <el-button type="danger" @click="onClickDel">作废</el-button>
          </template>
        </template> -->
      </template>

      <!-- 提交退费 -->
      <template v-if="curStep === 5">
        <el-button
          @click="onSubmitRefundFlag"
          :loading="submitLoading"
          type="primary"
        >提交</el-button>
      </template>

      <!-- 补发 -->
      <template v-if="curStep === 3 && !reasonInfo && reissuePermission">
        <template v-if="isReissue">
          <el-button
            @click="onSubmitReissue"
            :loading="submitLoading"
            type="primary"
          >提交</el-button>
          <el-button
            @click="onCancelReissue"
            :loading="submitLoading"
            type="primary"
            plain
          >取消</el-button>
        </template>
        <template v-else>
          <el-button
            :loading="submitLoading"
            @click="onReissue"
            type="primary"
          >补发</el-button>
        </template>
      </template>

      <el-button
        :loading="submitLoading"
        @click="visible=false"
      >关闭</el-button>
    </div>
    <el-dialog
      class="clinic-operate-dialog"
      :width="dialogWidths"
      append-to-body
      top="5vh"
      title="收费信息"
      :close-on-click-modal="false"
      :visible.sync="goPayFlage"
      style="cursor:default;"
    >
    <div class="clinic-operate-from">
      <el-row class="pay-content">
        <span style="padding:5px;font-size:14px;">订单金额</span>
        <span style="padding:5px;font-size:14px;">{{orderInfo.totalFee}}</span>
      </el-row>
      <el-row class="pay-content">
        <span style="padding:5px;font-size:14px;">订单信息</span>
        <!-- <span>订单编号</span> -->
        <span style="padding:5px;font-size:14px;">{{orderInfo.orderNo}}</span>
        <!-- <span>患者姓名</span> -->
        <span style="padding:5px;font-size:14px;">{{orderInfo.patientName}}</span>
        <!-- <span>医生姓名</span> -->
        <span style="padding:5px;font-size:14px;">{{orderInfo.docName}}</span>
      </el-row>
      <el-row class="pay-content">
        <span>处方信息</span>
        <div v-for="(item,index) in infoDrugs" :key="index" style="padding:5px;">
          <template v-if="item.orderCondition == 5">
          <el-col style="padding:5px;font-size:14px;color:#D3D3D3;" :span="4"><span>{{durtType(item.prescriptionType)}}</span></el-col>
          <el-col style="padding:5px;font-size:14px;color:#D3D3D3;" :span="20"><span>总计:</span>
          <span>{{parseFloat(item.totalPay).toFixed(2)}}</span>
          <span>药材费:</span>
          <span>{{parseFloat(item.drugCost).toFixed(2)}}</span>
          <span v-if="item.processCost">加工费:</span>
          <span v-if="item.processCost">{{parseFloat(item.processCost).toFixed(2)}}</span>
          <span style="font-size:13px;paddint-left:5px;">(已作废)</span>
          </el-col>
          </template>
          <template v-else>
            <el-col style="padding:5px;font-size:14px;" :span="4"><span>{{durtType(item.prescriptionType)}}</span></el-col>
          <el-col style="padding:5px;font-size:14px;" :span="20"><span>总计:</span>
          <span>{{parseFloat(item.totalPay).toFixed(2)}}</span>
          <span>药材费:</span>
          <span>{{parseFloat(item.drugCost).toFixed(2)}}</span>
          <span v-if="item.processCost">加工费:</span>
          <span v-if="item.processCost">{{parseFloat(item.processCost).toFixed(2)}}</span></el-col>
          </template>
        </div>
      </el-row>
      <el-row class="pay-content">
        <span>取药方式</span>
        <el-radio-group @change="addressTypeChange" v-model="orderInfo.deliveryType" style="margin-left:10px;">
        <el-radio :label=2>自取</el-radio>
        <el-radio :label=1>邮寄</el-radio>
        </el-radio-group>
      </el-row>
      <el-row class="pay-content" v-if="orderInfo.deliveryType == 1">
        <span>邮寄地址</span>
        <div style="padding:5px;">
        
        <el-col :span="6" style="padding:5px;background:#F5F5F5;">
            <el-input v-model="orderAddress.username" placeholder="收件人"></el-input>
        </el-col>
        <el-col :span="6" style="padding:5px;background:#F5F5F5;">
            <el-input v-model="orderAddress.phone" @input="onInoutCC" maxlength="11" :show-word-limit='false' placeholder="联系电话"></el-input>
          
        </el-col>
        <el-col :span="12" style="padding:5px;background:#F5F5F5;">
            <el-cascader
                  ref="cascader"
                  placeholder="收件人省市区"
                  v-model="cascaderValue"
                  @change="handleChange"
                  style="width: 100%"
                  :options="options"
                  :props="regionProps"
                >
                </el-cascader> 
          </el-col>
          <el-col :span="24" style="padding: 0 5px 5px 5px;background:#F5F5F5;">
            <el-input v-model="orderAddress.address" placeholder="详细地址"></el-input>
          
        </el-col>
        </div>
      </el-row>
      <el-row class="pay-content">
        <span style="margin-right:10px">收费优惠</span>
        <el-checkbox @change="shFeeCount" v-model="feeDiscount">减免费用<el-input @input="onInputChange" :disabled='!feeDiscount' v-model="diffFee" placeholder="0" style="width:70px;padding:0 5px 0 5px"></el-input>元</el-checkbox>
        
      <el-checkbox @change="shFeeCount" v-model="feedrugDiscount">药费折扣<el-input @input="onInputChange" :disabled='!feedrugDiscount' v-model="drugDiscount" placeholder="100" style="width:70px;padding:0 5px 0 5px"></el-input>%</el-checkbox>
      
        <el-checkbox @change="shFeeCount" v-model="feeallDiscount">整体折扣<el-input @input="onInputChange" :disabled='!feeallDiscount' v-model="allDiscount" placeholder="100" style="width:70px;padding:0 5px 0 5px"></el-input>%</el-checkbox>
        <span style="padding-left:10px">(例如:9折,输入90)</span>
      </el-row>
      <el-row class="pay-content">
        <span style="margin-right:10px">其他费用</span>
        <el-input v-model="otherFee" @input="onInputChange" placeholder="0" style="width:70px;padding:0 5px 0 5px"></el-input>
        <span>元</span>
      </el-row>
      <el-row class="pay-content">
        <span style="margin-right:10px">支付方式</span>
        <el-radio-group v-model="payWay">
        <el-radio :label=1>现金</el-radio>
        <el-radio :label=2>微信</el-radio>
        <el-radio :label=3>支付宝</el-radio>
        <el-radio :label=4>银行卡</el-radio>
        <el-radio :label=5>医保</el-radio>
    </el-radio-group>
      </el-row>
      
      <el-row class="pay-content" v-if="orderInfo.deliveryType == 1&&orderInfo.drugCost<100">
        <span style="margin-right:10px">邮寄费用</span>
        <span>10</span>
      </el-row>
      <el-row class="pay-content">
        <span style="margin-right:10px">优惠金额</span>
        <span>{{parseFloat(yhFee).toFixed(2)}}</span>
      </el-row>
      <el-row class="pay-content">
        <span style="margin-right:10px">流转金额</span>
        <span>{{parseFloat(lzFee).toFixed(2)}}</span>
      </el-row>
      <el-row class="pay-content">
        <span style="margin-right:10px">实收金额</span>
        <span>{{parseFloat(sjFee).toFixed(2)}}</span>
      </el-row>
    </div>
    <div slot="footer" class="dialog-footer">
      <span style="font-size:13px;color:#DC143C;text-align:left;margin-right:30px;">注：如若处方已作废，则不计入订单费用计算</span>
      <template><el-button  type="primary" @click="onClickSumbitPay" :loading="submitLoading">确认</el-button>
      <el-button @click="goPayFlage=false">关闭</el-button>
      </template>
    </div>
    </el-dialog>
  </el-dialog>
</template>

<script>
import { refund,updateOrderr, goPayApi,orderCheckOrder,orderConfirmOrder, comfireStock, reissue } from "@/api/charges/prescription";
import { getDetails, removeInfo} from '@/api/outpatientService/perscription';
import drugType from "@/views/storageRoom/drug/module/drugType";
import columnClickEdit from "@/components/ColumnClickEdit";
import { queryLazyTree } from "@/api/charges/logistics";
import { formatMoney } from "@/utils/index";
import asideForm from "./asideForm";
import personal from "./personal";
import { mapGetters } from "vuex";

export default {
  name: "operateForm",
  components: { asideForm, personal, columnClickEdit, drugType, queryLazyTree },
  props: {
    // 发货管理隐藏部分列
    isDeliver: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      regionProps: {
        lazy: true,
        lazyLoad(node, resolve) {
          queryLazyTree(node.value || "00").then(res => {
            let data = [];
            let level = node.level;
            res.forEach(item => {
              data.push({
                value: item.value,
                label: item.title,
                leaf: level >= 2
              });
            });
            resolve(data);
          });
        }
      },
      isRight:1,
      dataForm:1,
      infoDrugs: [],
      feeDiscount:false,
      feedrugDiscount:false,
      feeallDiscount:false,
      diffFee:0,
      yhFee:0,
      lzFee:0,
      sjFee:0,
      drugDiscount:100,
      allDiscount:100,
      payWay:1,
      otherFee:0,
      visible: false,
      init: false,
      height: 0,
      initIndex:0,
      operate: 0,
      consultInfo: {},
      addressInfoData: {},
      expenseDetails: [],
      expenseTotal: {},
      refundList: [],
      orderNo: null,
      payStatus:0,
      selections: [],
      loading: false,
      submitLoading: false,
      deliveryType: 2,
      orderNum:null,
      activeName:0,
      goPayFlage:false,
      isAllOrder:false,
      orderInfo:{},
      orderAddress:{},
      options: [],
      cascaderValue: [],
      orderCheckStatus:1,
      info: {}, // 当前正在浏览的处方
      curStep: null,
      isReissue: false, // 补发标识
      reasonInfo: null,
      incompleteRefund: false,
      reissuePermission: false,
    }
  },
  created() {
    this._initView();
  },
  computed: {
    ...mapGetters(["roles"]),
    style() {
      return {
        height: "calc(100% - 193px)"
      };
    },
    dialogWidth() {
      return window.innerWidth * 0.95 + "px";
    },
    dialogWidths() {
      return window.innerWidth * 0.6 + "px";
    }
  },
  methods: {
    formatMoney,
    addressTypeChange(){
      this.cascaderValue = [];
      this.shFeeCount();
    },
    shFeeCount(){
      this.diffFee = this.feeDiscount?this.diffFee:0;
      this.drugDiscount = this.feedrugDiscount?this.drugDiscount:100;
      this.allDiscount = this.feeallDiscount?this.allDiscount:100;
      this.lzFee = parseFloat(this.orderInfo.cirulationCost?this.orderInfo.cirulationCost:0);
      if(this.orderInfo.deliveryType == 1&&this.orderInfo.drugCost*parseFloat(this.drugDiscount?this.drugDiscount:100)/100.0*parseFloat(this.allDiscount?this.allDiscount:100)/100.0<100){
      this.sjFee = (parseFloat(this.orderInfo.drugCost)*parseFloat(this.drugDiscount?this.drugDiscount:100)/100.0  + parseFloat(this.otherFee?this.otherFee:0) + parseFloat(this.orderInfo.machinFee?this.orderInfo.machinFee:0))*parseFloat(this.allDiscount?this.allDiscount:100)/100.0 -parseFloat(this.diffFee?this.diffFee:0) + 10.0;
      this.yhFee = parseFloat(this.orderInfo.totalFee) + parseFloat(this.otherFee?this.otherFee:0) - parseFloat(this.sjFee) + 10;
      }else{
       this.sjFee = (parseFloat(this.orderInfo.drugCost)*parseFloat(this.drugDiscount?this.drugDiscount:100)/100.0 + parseFloat(this.otherFee?this.otherFee:0) + parseFloat(this.orderInfo.machinFee?this.orderInfo.machinFee:0))*parseFloat(this.allDiscount?this.allDiscount:100)/100.0 -parseFloat(this.diffFee?this.diffFee:0);
       this.yhFee = parseFloat(this.orderInfo.totalFee) + parseFloat(this.otherFee?this.otherFee:0) - parseFloat(this.sjFee);
      }
      this.sjFee = this.sjFee - this.lzFee;
      
      // this.sjFee = (parseFloat(this.orderInfo.totalFee) + parseFloat(this.otherFee?this.otherFee:0))*parseFloat(this.allDiscount?this.allDiscount:100)/100.0 - (parseFloat(this.orderInfo.drugCost) -(parseFloat(this.orderInfo.drugCost)*parseFloat(this.drugDiscount?this.drugDiscount:100))/100.0) - parseFloat(this.diffFee?this.diffFee:0)
      
    },
    onOkOrder() {
      this.submitLoading = true;
      updateOrderr(this.orderInfo.orderNo).then(() => {
        this._success();
      }).catch(() => {
        this.submitLoading = false;
      });
    },
    onInoutCC(){
      this.orderAddress.phone = this.orderAddress.phone.replace(/[^\d]/g, '')
    },
    onInputChange(){
      this.shFeeCount();
    },
    handleClick(tab) {
      if(this.infoDrugs) {
        this.initIndex = Number(this.activeName);
        this.info = this.infoDrugs[tab.index];
        var temData = this.info.infoDrugs;
        this.info.infoDrugs = [];
        temData.forEach(el => {
          if(el.isCirulation != 1){
            this.info.infoDrugs.push(el);
          }
        });
        
        var oMap = this.infoDrugs[tab.index];
        this.operate = oMap.payStatus;
        this.orderCheckStatus = oMap.orderCondition;
        // 设置流程
        let refundFlag = this.orderInfo.orderType === 2 ? this.orderInfo.refundFlag : 2;
        this.visible = false;
        this.curStep = this.stepStatus(this.operate, this.orderCheckStatus, refundFlag);
        this.visible = true;
      }
    },
    onClickPay(){
      this.otherFee = 0;
      this.orderAddress={};
        this.cascaderValue = [];
      this.goPayFlage = true;
    },
    onClickSumbitPay(){
      var dataMap = {orderAddress:{}};
      dataMap.allDiscount = this.allDiscount;
      dataMap.deliveryType = this.orderInfo.deliveryType;
      dataMap.diffFee = this.diffFee;
      dataMap.drugDiscount = this.drugDiscount;
      dataMap.orderNo = this.orderInfo.orderNo;
      dataMap.otherFee = this.otherFee;
      dataMap.payWay = this.payWay;
      if(this.orderInfo.deliveryType == 1){
      dataMap.orderAddress.address = this.orderAddress.address;
      dataMap.orderAddress.area = this.orderAddress.area;
      dataMap.orderAddress.areaCode = this.orderAddress.areaCode;
      dataMap.orderAddress.city = this.orderAddress.city;
      dataMap.orderAddress.cityCode = this.orderAddress.cityCode;
      dataMap.orderAddress.orderNo = this.orderAddress.orderNo;
      dataMap.orderAddress.phone = this.orderAddress.phone;
      dataMap.orderAddress.province = this.orderAddress.province;
      dataMap.orderAddress.provinceCode = this.orderAddress.provinceCode;
      dataMap.orderAddress.username = this.orderAddress.username;
      if(!this.orderAddress.address||!this.orderAddress.area||!this.orderAddress.city||!this.orderAddress.province||!this.orderAddress.username||!this.orderAddress.phone){
        this.$message.error("邮寄地址不能为空");
         return;
      }
      }
      
      goPayApi(dataMap).then(() => {
        this.goPayFlage = false;
        this._success();
      })
    },
    _initView() {
      this._loadLazyTree({
        children: this.options,
        parent: "00"
      });
    },
    _loadLazyTree({ parent, children}) {
      queryLazyTree(parent).then(res => {
        res.forEach(item => {
          children.push({
            value: item.value,
            label: item.title
          });
        });
      });
    },
    handleChange() {
      let nodes = this.$refs.cascader.getCheckedNodes()[0].pathLabels;
      this.orderAddress.province = nodes[0];
      this.orderAddress.city = nodes[1];
      this.orderAddress.area = nodes[2];
      this.orderAddress.provinceCode = this.cascaderValue[0];
      this.orderAddress.cityCode = this.cascaderValue[1];
      this.orderAddress.areaCode = this.cascaderValue[2];
      this.orderAddress.orderNo = this.orderInfo.orderNo;
    },
    durtType(type) {
      let res = "";
      switch (type) {
        case 1:
          res = '饮片'
          break;
        case 2:
          res = '成药'
          break;
        case 3:
          res = '颗粒剂'
          break;
        case 4:
          res = '输液处方'
          break;
        case 5:
          res = '敷贴处方'
          break;
      }
      return res;
    },
    durtSource(type){
      switch (type) {
            case 1:
                return ''
                break;
            case 2:
                return '（协定方）'
                break;
            default:
                break;
        }
    },
    open(row, index, typeData, right) {
      this.isRight = right;
      this.dataForm = typeData;
      this.initIndex = index;
      this.isReissue = false;
      this.selections = [];
      this.incompleteRefund = false;
      if(index == 99999){
        this.isAllOrder = true;
      }
      if(this.$refs.asideForm) {
        this.$refs.asideForm.resetForm();
      }
      this._checkPermission();
      this.refresh(row.id, true);
    },
    // 部分退费处理
    openRefundHandle(id) {
      this.isRight = undefined;
      this.dataForm = undefined;
      this.initIndex = 99999;
      this.isReissue = false;
      this.selections = [];
      this.incompleteRefund = true;
      if(this.$refs.asideForm) {
        this.$refs.asideForm.resetForm();
      }
      this.refresh(id, false);
    },
    // 刷新
    refresh(id, openPrint) {
      this.loading = true;
      if(!id) {
        id = this.orderInfo.id;
      }
      getDetails(id).then(res => {
        this.handleData(res, openPrint);
        this.loading = false;
      });
    },
    handleData(data, openPrint) {
      // 取货方式
      this.deliveryType = data.order.deliveryType;
      // 问诊信息
      let consult = data.consult;
      this.consultInfo = {    
        patientName: data.order.patientName,
        consultDocName : data.order.docName,
        patientSex: data.order.patientSex,
        patientAge: data.order.patientAge,
        orderTime: data.order.orderTime,
        consultNo: data.order.consultNo
      };
      if(data.consult) {
        this.consultInfo.consultDepartName = consult.consultDepartName;
        this.consultInfo.consultType = consult.consultType;
        this.consultInfo.diagnosis = consult.diagnosis;
      }
      this.addressInfoData = data.orderAddress;
      this.orderInfo = data.order;
      this.sjFee = this.orderInfo.totalFee;
      this.orderInfo.deliveryType = this.orderInfo.deliveryType?this.orderInfo.deliveryType:2;

      if(this.orderInfo.oldOrderNo) {
        this.reasonInfo = {
          oldOrderNo: this.orderInfo.oldOrderNo,
          reissueReason: this.orderInfo.reissueReason,
        };
      } else {
        this.reasonInfo = null;
      }

      // 药品列表
      this.infoDrugs = data.order.infos;
      // 费用明细
      this.expenseDetails = data.expenseDetails;
      // if(this.operate == 0){
      var eDtailList = [];
      this.infoDrugs.forEach(ed => {
        var dMap = {name:null,money:null,processCost:null,drugCost:null,orderCondition:null,payStatus:null};
        dMap.name = this.durtType(ed.prescriptionType);
        dMap.money = ed.totalPay;
        dMap.processCostName = '加工费';
        dMap.drugCostName = '药费';
        dMap.drugCost = ed.drugCost;
        dMap.processCost = ed.processCost;
        dMap.orderCondition = ed.orderCondition;
        dMap.payStatus = ed.payStatus;
        eDtailList.push(dMap);
      });
      this.expenseDetails = eDtailList;
      // }
      
      this.expenseTotal = this.orderInfo;
      this.expenseTotal.refundExp = data.refundExp;
      this.expenseTotal.refundOtherFee = data.refundOtherFee;
      if(this.initIndex == 99999) {
        this.activeName = '0';
      } else {
        this.activeName = this.initIndex.toString();
      }
      if(this.infoDrugs) {
        this.info = this.infoDrugs[this.activeName];
        var temData = this.info.infoDrugs;
        this.info.infoDrugs = [];
        temData.forEach(el => {
          if(el.isCirulation != 1) {
            this.info.infoDrugs.push(el);
          }
        });
        if(this.initIndex == 99999) {
          var oMap = this.infoDrugs[0];
          this.orderCheckStatus = oMap.orderCondition;
          this.operate = oMap.payStatus;
        } else {
          var oMap = this.infoDrugs[this.activeName];
          this.operate = oMap.payStatus;
          this.orderCheckStatus = oMap.orderCondition;
        }
      }
      if(this.$refs.table) {
        this.$refs.table.clearSelection();
      }
      // 订单号
      this.orderNo = data.order.id;
      this.orderNum = data.order.orderNo;
      this.payStatus = data.order.payStatus;
      // 退费原因
      this.refundList = data.prescriptionRefunds;

      if(this.operate === 3) {
        this.infoDrugs.forEach(item => {
          item.refundNum = 0;
        });
        this.expenseTotal.refundNum = 0;
      }

      if(this.orderInfo.cirulationCost === this.orderInfo.drugCost && this.orderInfo.orderType == 2) {
        this.$message.error("该订单药品已全部流转，可正常审方调剂，不扣除实际库存");
      } else {
        // 打开打印页面
        if(openPrint && (this.operate === 1 || this.operate === 2) && (this.orderCheckStatus == 1 || this.orderCheckStatus == 2)) {
          this.onPrintDetails();
        }
      }

      // 设置流程
      let refundFlag = this.orderInfo.orderType === 2 ? this.orderInfo.refundFlag : 2;
      this.curStep = this.stepStatus(this.operate, this.orderCheckStatus, refundFlag);
      this.visible = true;
    },
    // 设置流程,0-待收费,1-已收费,2-已审核,3-已调剂,4-已退费,5-退费中
    stepStatus(payStatus, orderCondition, refundFlag) {
      let res = 0;
      if(this.incompleteRefund) {
        // 部分退费点击去处理
        return 5;
      }
      switch(payStatus) {
        case 0:
          // 待支付
          res = 0;
          break;
        case 1:
        case 2:
          if(orderCondition === 1) {
            // 已收费: 待审方
            res = 1;
          } else if(orderCondition === 2) {
            // 已审核: 调剂中
            res = 2;
          } else {
            // 已调剂: 待发货，已取消，已完成
            res = 3;
          }
          break;
        case 3:
          // 已退费: 已退款
          if(refundFlag === 1) {
            res = 5;
          } else {
            res = 4;
          }
          
          break;
      }
      return res;
    },
    onChangeDiscount({ row, value }) {
      row.price = row.quantity * row.price * (value / 100);
      row.discount = value;
    },
    onChangeTuifei({ row, value }) {
      row.refundNum = value;
      this._updateRefundNum();
    },
    discountText(discount) {
      let num = Number(discount);
      return num * 100 + "%";
    },
    onClickCheck(type) {
      let codeNo = this.infoDrugs[this.activeName].infoNo;
      switch(type) {
        case 2:
          // 审方
          this.submitLoading = true;
          orderCheckOrder({codeNo, type: 2 }).then(() => {
            this._checkSuccess();
          }).catch(() => {
            this.submitLoading = false;
          });
          break;
        case 5:
          // 调剂
          this.submitLoading = true;
          orderConfirmOrder({codeNo, type: 2 }).then(() => {
            this._checkSuccess();
          }).catch(() => {
            this.submitLoading = false;
          });
          break;
      }
    },
    onRefund() {
      // 前往退费
      this.visible = false;
      this.operate = 3;
      this.$nextTick(() => {
        this.visible = true;
      });
    },
    // 补发选择
    onSelectionChange(rows) {
      // console.log(".............. onSelectionChange = ", rows);
      this.selections = rows;
      // this._updateRefundNum();
    },
    onSubmitRefund() {
      if(this.selections.length === 0) {
        this.$message.error("请选择要提交的数据!");
        return;
      }
      let refundMsg = this.$refs.asideForm.getRefundMsg();
      let criterias = [];
      this.selections.forEach(item => {
        criterias.push({
          infoDrugId: item.id,
          refundNum: item.refundNum
        });
      });
      if(!refundMsg) {
        this.$message.error("请选择退款原因!");
        return;
      }
      this.submitLoading = true;
      refund(criterias, this.orderNo, refundMsg).then(() => {
        this._success();
      });
    },
    onPrintDetails() {
      if(this.orderInfo.cirulationCost > 0 && this.orderInfo.infos.length == 0){
        this.$message.error("该处方药品已经全部流转！");
      }else{
      this.$parent.onOperateRow(6, this.orderInfo.id);
      }
    },
    onClickDel() {
      let that = this;
      let id = this.infoDrugs[this.activeName].id;
      this.$confirm('是否确认作废该处方？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        let deleParams = { id };
        that.submitLoading = true;
        removeInfo(deleParams).then(() => {
          that._success();
        }).catch(() => {
          that.submitLoading = false;
        });
      });
    },
    _success() {
      this.$notify({
        title: "操作成功",
        type: "success"
      });
      this.$emit("refresh");
      this.submitLoading = false;
      this.visible = false;
      this.$refs.asideForm.resetForm();
    },
    _updateRefundNum() {
      let refundNum = 0;
      this.selections.forEach(item => {
        refundNum += item.refundNum * item.price;
      });
      let expenseTotal = JSON.parse(JSON.stringify(this.expenseTotal));
      expenseTotal.refundNum = refundNum;
      this.expenseTotal = expenseTotal;
    },
    _handLogistics(item) {
      let description = "[" +item.acceptAddress + "]" + item.remark;
      let title = "";
      switch(item.opcode) {
        case 30:
        case 31:
        case 130:
        case 123:
          title += "运输中";
          break;
        case 33:
        case 70:
          title += "派件异常";
          break;
        case 50:
          title += "已揽件";
          break;
        case 80:
        case 8000:
          title += "已签收";
          break;
        case 44:
          title += "派送中";
          break;
        case 607:
          title += "待取件";
          break;
        case 99:
          title += "转寄中";
          break;
        case 648:
          title += "已退回";
          break;
      }
      title += " " + item.acceptTime;

      return {
        title: title,
        description: description
      };
    },
    // 审方|调剂成功
    _checkSuccess() {
      this.$notify({
        title: "操作成功",
        type: "success"
      });
      this.refresh(this.orderInfo.id, false);
      this.$emit("refresh");
      this.submitLoading = false;
      this.$refs.asideForm.resetForm();
    },
    onSubmitRefundFlag() {
      let type = this.$refs.asideForm.refundType;
      let data = {
        orderNo: this.orderNum,
        type,
      }
      if(type !== 0 && type !== 1 && type !== 2) {
        this.$message.error("请选择库存处理方式");
        return;
      }
      this.submitLoading = true;
      comfireStock(data).then(() => {
        this.submitLoading = false;
        this._success();
      }).catch(error => {
        this.submitLoading = false;
        console.error(error);
      });
    },
    selectableReissue() {
      if(this.info.prescriptionType === 1 || this.info.prescriptionType === 3) {
        return false;
      }
      return true;
    },
    onReissue() {
      let { infoDrugs, prescriptionType } = this.info;
      this.isReissue = true;
      this.$nextTick(() => {
        infoDrugs.forEach(e => {
          if(prescriptionType === 1 || prescriptionType === 3) {
            e.operateNum = e.dose;
            this.$refs.table.toggleRowSelection(e, true);
          } else {
            e.operateNum = undefined;
          }
        });
      });
    },
    onCancelReissue() {
      let { infoDrugs } = this.info;
      this.$refs.table.clearSelection();
      this.isReissue = false;

      infoDrugs.forEach(e => {
        e.operateNum = null;
      });
    },
    onSubmitReissue() {
      if(!this.selections || !this.selections.length) {
        this.$message.error("请选择补发的药品");
        return;
      }
      for (let item of this.selections) {
        if(item.operateNum === 0) {
          this.$message.error(`药品"${item.drugName}"补发数量不能为0`);
          return;
        }
        if(!item.operateNum) {
          this.$message.error(`请填写药品"${item.drugName}"补发数量`);
          return;
        }
      }
      let { infoNo, prescriptionType } = this.info;
      let form = this.$refs.asideForm.getReissueForm();
      if(!form.dosageNum && prescriptionType != 2) {
        this.$message.error("请填写剂数");
        return;
      }
      if(!form.reissueReason) {
        this.$message.error("请填写补发原因");
        return;
      }
      let data = {
        reissueReason: form.reissueReason,
        num: form.dosageNum,
        drugList: [],
        infoNo,
      };
      this.selections.forEach(item => {
        data.drugList.push({
          id: item.id,
          drugName: item.drugName,
          quantity: item.operateNum,
        });
      });
      this.submitLoading = true;
      reissue(data).then(() => {
        this.submitLoading = false;
        this._success();
      }).catch(error => {
        this.submitLoading = false;
        console.error(error);
      });
    },
    _checkPermission() {
      let permissionRoles = ['admin','order:reissue'];
      this.reissuePermission = this.roles.some(role => {
        return permissionRoles.includes(role);
      });
    }
  }
}
</script>
<style>
.pay-content{
    margin: 10px;
}
</style>